//
//  ZSY_SearchViewController.m
//  ZSY_BreadTrip
//
//  Created by 张诗宇 on 16/1/6.
//  Copyright © 2016年 张诗宇. All rights reserved.
//

#import "ZSY_SearchViewController.h"
#import "ZSY_SearchModel.h"
#import "ZSY_SearchTableViewCell.h"
#import "ZSY_SearchEndViewController.h"
#import "ZSY_SearchEndModel.h"

@interface ZSY_SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *inlandArray;
@property (nonatomic, retain) NSMutableArray *foreignArray;

@property (nonatomic, retain) ZSY_BaseTableView *myTableView;

@property(nonatomic,retain)UISearchBar *mySearchBar;
//@property(nonatomic,retain)UISearchDisplayController *searchDC;
@property(nonatomic,retain)NSMutableArray *searchUsersArray;
@property (nonatomic, retain) NSMutableArray *searchTripsArray;

@property(nonatomic,retain)UISearchController *searchController;

@property (nonatomic, retain) NSMutableArray *userName;

@end

@implementation ZSY_SearchViewController

- (void)dealloc {
    [_inlandArray release];
    [_foreignArray release];
    [_mySearchBar release];
    [_myTableView release];
    [_searchController release];
    [_searchTripsArray release];
    [_searchUsersArray release];
    [_userName release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:243 / 255.0 blue:233 / 255.0 alpha:1];
    self.view.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 64);
    
    self.inlandArray = [NSMutableArray array];
    self.foreignArray = [NSMutableArray array];
    self.searchUsersArray = [NSMutableArray array];
    self.searchTripsArray = [NSMutableArray array];
    self.userName = [NSMutableArray array];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add_new_poi_back_btn"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
//    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.delegate = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    
    self.myTableView = [[ZSY_BaseTableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStyleGrouped];
//    self.myTableView.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:243 / 255.0 blue:233 / 255.0 alpha:1];
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    
    self.myTableView.separatorStyle = NO;

    // 解析热门搜索的数据
    // AFN请求数据
    [ZSY_AppTools creatingDataTask:@"http://api.breadtrip.com/v2/index/?lat=38.88262035734694&lng=121.5394745257025&sign=e5c96fa9bed9fca0d3b19b5a51476b0f" parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        NSDictionary *dic = resuposeObject;
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        
         // 解析search_data,搜索栏数据
         NSArray *searchArray = [dataDic objectForKey:@"search_data"];
         for (NSDictionary *twoDic in searchArray) {
         if ([[twoDic objectForKey:@"title"] isEqualToString:@"国外热门目的地"]) {
         // 国外热门目的地
         NSArray *elementsArray = [twoDic objectForKey:@"elements"];
             for (NSDictionary *elementDic in elementsArray) {
                 ZSY_SearchModel *model = [[ZSY_SearchModel alloc] init];
                 [model setValuesForKeysWithDictionary:elementDic];
                 [self.foreignArray addObject:model];
                 [model release];
             }
             
             
         } else if ([[twoDic objectForKey:@"title"] isEqualToString:@"国内热门目的地"]) {
         // 国内热门目的地
             NSArray *elementsArray = [twoDic objectForKey:@"elements"];
             for (NSDictionary *elementDic in elementsArray) {
                 ZSY_SearchModel *model = [[ZSY_SearchModel alloc] init];
                 [model setValuesForKeysWithDictionary:elementDic];
                 [self.inlandArray addObject:model];
//                 NSLog(@"886  ===== %ld", _inlandArray.count);
                 [model release];
             }

         }
         
         }
        [self.myTableView reloadData];
         
    }];

    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    ZSY_SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ZSY_SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    if (indexPath.section == 1) {
        
            NSLog(@"%ld", _inlandArray.count);
            cell.allArray = _inlandArray;
    } else {
        cell.allArray = _foreignArray;
    }
    
    return cell;
}
// 设置section头部样式
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ZSY_BaseView *view = [[ZSY_BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
//    view.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:243 / 255.0 blue:233 / 255.0 alpha:1];
    ZSY_BaseLabel *sectionLabel = [[ZSY_BaseLabel alloc] initWithFrame:CGRectMake(0, 25, WIDTH, 20)];

    if (section == 1) {
        sectionLabel.text = @"国内热门目的地";
        
        sectionLabel.textAlignment = NSTextAlignmentCenter;
    } else {
        sectionLabel.text = @"国外热门目的地";
        sectionLabel.textAlignment = NSTextAlignmentCenter;
    }
    [view addSubview:sectionLabel];
    return view;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 30 * _foreignArray.count;
    }else {
        
        return 30 * _inlandArray.count;
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

#if 0

// 搜索状态时会走这个方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
    NSLog(@"===%@",searchString);
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/search/?key=%@&sign=692beea8117847e3ebd5108fc8db1da8", searchString];
    /**
     *  由于url的一个参数可能为汉字,我们需要用下面的方法转换一下字符串,才能被AFN使用
     */
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    NSLog(@"url = %@", url);
    
    [ZSY_AppTools creatingDataTask:url parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
//        NSLog(@"%@", resuposeObject);
        NSDictionary *dataDic = [resuposeObject objectForKey:@"data"];
        NSArray *userArray = [dataDic objectForKey:@"users"];
        for (NSDictionary *dic in userArray) {
            ZSY_SearchUserModel *searchUser = [[ZSY_SearchUserModel alloc] init];
            [searchUser setValuesForKeysWithDictionary:dic];
            [self.searchArray addObject:searchUser];
            [searchUser release];
        }
        
        
    }];

    
//    ZSY_SearchEndViewController *searchVC = [[ZSY_SearchEndViewController alloc] init];
//    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:searchVC];
//    
//    [self presentViewController:naVC animated:YES completion:^{
//        
//        
//    }];
    
}

#endif



// 当点击键盘的search按钮时会走这个方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    [searchBar resignFirstResponder];
    

    NSLog(@"∂≈∂ßƒƒßƒ®∑®˙˚∆®˚¬®");
    NSString *searchString = [self.searchController.searchBar text];
    
    NSLog(@"===%@",searchString);
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/search/?key=%@&sign=692beea8117847e3ebd5108fc8db1da8", searchString];
    [self.searchTripsArray removeAllObjects];
    [self.searchUsersArray removeAllObjects];
    [self.userName removeAllObjects];
    /**
     *  由于url的一个参数可能为汉字,我们需要用下面的方法转换一下字符串,才能被AFN使用
     */
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //    NSLog(@"url = %@", url);
    
    [ZSY_AppTools creatingDataTask:url parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        //        NSLog(@"%@", resuposeObject);
        NSDictionary *dataDic = [resuposeObject objectForKey:@"data"];
        NSArray *userArray = [dataDic objectForKey:@"users"];
        for (NSDictionary *dic in userArray) {
            ZSY_SearchUserModel *searchUser = [[ZSY_SearchUserModel alloc] init];
            [searchUser setValuesForKeysWithDictionary:dic];
            [self.searchUsersArray addObject:searchUser];
            [self.userName addObject:searchUser.name];
            [searchUser release];
        }
        
        NSArray *tripArray = [dataDic objectForKey:@"trips"];
        for (NSDictionary *tripDic in tripArray) {
            ZSY_SearchTripModel *searchTrip = [[ZSY_SearchTripModel alloc] init];
            [searchTrip setValuesForKeysWithDictionary:tripDic];
            [self.searchTripsArray addObject:searchTrip];
            [searchTrip release];
        }
        
        
    }];

    
    
    ZSY_SearchEndViewController *searchVC = [[ZSY_SearchEndViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:searchVC];
    
    [self presentViewController:naVC animated:YES completion:^{
        NSLog(@"%----ld", self.searchUsersArray.count);
        searchVC.tripArray = self.searchTripsArray;
        searchVC.allArray = self.searchUsersArray;
        searchVC.searchField.text = searchString;
        searchVC.userName = _userName;
        
    }];
}



//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

- (void)leftButtonAction:(UIBarButtonItem *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonAction:(UIBarButtonItem *)button {
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
